package top.huxy.boot.controller.publicly;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.HttpEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.huxy.boot.annotation.RequestRemake;
import top.huxy.boot.util.obj.Result;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author HuXY
 */
@RestController
public class HttpProxy {

    @RequestRemake("百度位置转化代理")
    @GetMapping("/baiduMapLocationGeoconvProxy")
    public Result baiduMapLocationGeoconvProxy(@RequestParam("coords") String coords) {
        String url = "https://api.map.baidu.com/geoconv/v1/?coords=" + coords + "&from=1&to=5&ak=yKXGoYsU2LUSutPvnWvfG7ZKngzoQW6h";
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            ClassicHttpRequest http = new HttpGet(url);
            try (CloseableHttpResponse response = httpclient.execute(http)) {
                int code = response.getCode();
                HttpEntity entity = response.getEntity();
                try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
                    entity.writeTo(byteArrayOutputStream);

                    byte[] bytes = byteArrayOutputStream.toByteArray();

                    return new Result(code, code + "", new String(bytes));
                }
            }
        } catch (IOException e) {
            return Result.serverError(e.getMessage());
        }
    }
}
